<template>
  <div class="gobang-Qp">
    <div @click="onclick(index)" v-for="(item, index) in pieces" :key="index" :id="'gobang' + index"
      class="gobang-Qp-erzi">
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, watch } from 'vue';
import { Piece } from '../ts/piece';
import type { outcome, pieceoption, sORj } from '../ts/type';
import createWebSocket from '../ts/websocket'
const sORjdata = getCurrentInstance()?.appContext.app.config.globalProperties.$sORj
//监听房间是否创建成功
watch(getCurrentInstance()?.appContext.app.config.globalProperties.$sORj, (newValue, oldValue) => {
  sORjdata.value = newValue.value
  console.log(newValue, '更新的值');


})
//定义所棋盘上所有的棋子的集合
const pieces = ref<(Piece | null)[]>([])
const type = ref<'h' | 'b'>('h')
const PiecesDom = ref<HTMLDivElement[]>([])
const props = defineProps<{
  socket: WebSocket
}>()
//初始化棋子
for (let i = 0; i < 225; i++) {
  pieces.value?.push(null)
}

//点击棋盘落棋
const onclick = (index: number) => {
  console.log(sORjdata.value, '这个是sorj');

  //判断是否有两个玩家加入房间
  if (sORjdata.value.data.count == '2') {
    //初始化棋子参数
    const option: pieceoption = {
      x: Math.floor(index % 15),
      y: Math.floor(index / 15),
      type: type.value == 'h' ? 'b' : 'h',
      dom: document.querySelector('#gobang' + index)!
    }
    //判断当前位置没有棋子
    if (!pieces.value[index]) {
      type.value = type.value == 'h' ? 'b' : 'h'
      pieces.value[index] = new Piece(option)
      //判断是否胜利
      const pieceOutcome: outcome = pieces.value[index]?.outCome(option, pieces.value as (Piece | null)[])!
      //创建的棋子的div的dom
      PiecesDom.value.push(pieceOutcome.dom!)
      if (pieceOutcome.outcome) {
        setTimeout(() => {
          alert(pieceOutcome.type == 'h' ? '小黑子胜利' : '大白胜利')
          pieces.value = []
          for (let i = 0; i < 225; i++) {
            pieces.value?.push(null)
          }
          PiecesDom.value.forEach(item => {
            item.remove()
          })
        })

      }
    }



    props.socket.send(JSON.stringify({ code: 'pieces', data: pieces.value, index }))

  } else {
    alert('还差一个人进入房间')
  }

}


</script>
<style lang="scss" scoped>
.gobang-Qp {
  width: 620px;
  height: 620px;
  margin: auto;
  background-color: rgba(247, 80, 15, 0.368);
  display: flex;
  flex-wrap: wrap;
  position: absolute;
  left: 0;
  top: 0;
  padding: 10px;

  .gobang-Qp-erzi {
    height: 40px;
    width: 40px;
    border: 1px solid rgba(253, 45, 45, 0);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>